package models

import (
	"github.com/astaxie/beego"
	//"github.com/astaxie/beego/logs"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

var db *gorm.DB

func init() {
	//注册 model，创建表
	//dbAlia := beego.AppConfig.String("db_alias")

	dbType := beego.AppConfig.String("db_type")
	//数据库名称
	dbName := beego.AppConfig.String("db_name")
	//数据库连接用户名
	dbUser := beego.AppConfig.String("db_user")
	//数据库连接用户名
	dbPwd := beego.AppConfig.String("db_pwd")
	//数据库IP（域名）
	dbHost := beego.AppConfig.String("db_host")
	//数据库端口
	dbPort := beego.AppConfig.String("db_port")
	//数据库字符类型
	//dbCharset := beego.AppConfig.String("db_charset" )
	// set default database
	//orm.RegisterDataBase("default", "mysql", "username:password@tcp(127.0.0.1:3306)/db_name?charset=utf8", 30)
	// 参数1        数据库的别名，用来在 ORM 中切换数据库使用
	// 参数2        driverName
	// 参数3        对应的链接字符串
	//db, err = gorm.Open("mysql", "root:123456@/qomo?charset=utf8&parseTime=True&loc=Local")
	var err error
	db, err = gorm.Open(dbType, dbUser+":"+dbPwd+"@tcp("+dbHost+":"+dbPort+")/"+dbName+"?charset=utf8&parseTime=True&loc=Local")
	//defer db.Close()
	if err != nil {
		panic("failed to connect database", )
	}
	// 自动同步表结构
	//db.SetLogger(logs.GetLogger("orm"))
	//db.LogMode(true)
	db.AutoMigrate(&User{}, &Role{}, &Menu{}, &Dict{})
	db.AutoMigrate(&LgUser{}, &AssetLabel{}, &AssetIdc{}, &Asset{}, &AssetOs{}, &AssetPartitions{}, &AssetNic{})
	db.AutoMigrate(&LogUser{}, &LogTask{})
	db.AutoMigrate(&CmdRecord{}, &OpsScript{})
	db.AutoMigrate(&ItemPrj{}, &ItemPlatfm{}, &ItemRelease{},&ItemBranch{})

	beego.BConfig.WebConfig.Session.SessionProvider = "mysql"
	beego.BConfig.WebConfig.Session.SessionProviderConfig = dbUser + ":" + dbPwd + "@tcp(" + dbHost + ":" + dbPort + ")/" + dbName + "?charset=utf8&parseTime=True&loc=Local"
}
